package com.example.demo.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;


@ControllerAdvice
@ResponseBody
public class ResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true; // 返回true才会继续执行下面的代码
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 检查 body 是否为验证码类型
        if (body instanceof byte[]) {
            return body; // 如果是字节数组，直接返回，不经过其他处理
        }

        if (body instanceof HashMap) {
            return body;
        }
        if (body instanceof Integer){
            int num = (int) body;
            if (num <= 0) {
                return AjaxResult.fail(-1,"抱歉，本次操作失败，请稍后再试！");
            }
        }

        if (body == null) {
            return AjaxResult.fail(-1,"抱歉，查询失败！");
        }
        if (body instanceof String) {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(body);
        }

        return AjaxResult.success(body);
    }

}
